﻿using CToolsWin.BLL.sys;
using Model.sys;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Security.AccessControl;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace CToolsWin.Files
{
    public partial class FolderTree : Form
    {
        List<Task> listTask = new List<Task>();
        sys_DirectoryInfo info = new sys_DirectoryInfo();
        private bool loadSuccess = true;
        public FolderTree()
        {
            InitializeComponent();
        }

        private void btnSelectFolder_Click(object sender, EventArgs e)
        {
            if (loadSuccess)
            {
                FolderBrowserDialog folder = new FolderBrowserDialog();
                folder.SelectedPath = txtFolderPath.Text;
                folder.ShowDialog();
                txtFolderPath.Text = folder.SelectedPath;
            }
        }

        public sys_DirectoryInfo GetFolderInfo(string path, string parentPath = "")
        {
            var directory = new System.IO.DirectoryInfo(path);
            if (directory.Exists)
            {
                sys_DirectoryInfo folder = new sys_DirectoryInfo();
                folder.Name = directory.Name;
                folder.FullName = directory.FullName;
                folder.ParentPath = parentPath;
                folder.CreationTime = directory.CreationTime;
                folder.LastWriteTime = directory.LastWriteTime;
                if (directory.Attributes.HasFlag(System.IO.FileAttributes.System) == false || directory.Parent == null)
                {
                    folder.ListFile = directory.GetFiles().Select(GetFileInfo).ToList();
                    folder.ListChilder = directory.GetDirectories().Select(s => GetFolderInfo(s.FullName, directory.FullName)).ToList();
                }
                return folder;
            }
            return null;
        }

        public sys_FileInfo GetFileInfo(System.IO.FileInfo file)
        {
            var fileInfo = new sys_FileInfo()
            {
                Name = file.Name,
                FullName = file.FullName,
                Extension = file.Extension != "" ? file.Extension.Substring(1) : "",
                LastWriteTime = file.LastWriteTime,
                CreationTime = file.CreationTime,
                Size = file.Length//,
                //MD5 = file.Length > 1024 * 1024 * 1024 ? "" : Common.Tools.Encrypt.MD5.Encrypt(file.OpenRead())
            };
            if (file.Length < 1024 * 1024 * 1024)
            {
                var task = new TaskFactory().StartNew(() =>
                 {
                     using (System.IO.FileStream fs = file.OpenRead())
                     {
                         fileInfo.MD5 = Common.Tools.Encrypt.MD5.EncryptSimple(fs);
                     }
                 });
                listTask.Add(task);
            }
            return fileInfo;
        }

        public TreeNode SetTree(sys_DirectoryInfo folder)
        {
            TreeNode treeNode = new TreeNode(folder.Name);

            if (folder.ListFile != null)
            {
                foreach (var item in folder.ListFile)
                {
                    TreeNode treeNode1 = new TreeNode(item.Name + "(" + item.MD5 + ")");
                    treeNode.Nodes.AddRange(new TreeNode[] { treeNode1 });
                }
            }
            if (folder.ListChilder != null)
            {
                foreach (var item in folder.ListChilder)
                {
                    TreeNode treeNode1 = SetTree(item);
                    treeNode.Nodes.AddRange(new TreeNode[] { treeNode1 });
                }
            }
            return treeNode;
        }

        private void btnSeeTree_Click(object sender, EventArgs e)
        {
            if (string.IsNullOrWhiteSpace(txtFolderPath.Text) == false)
            {
                if (txtFolderPath.Text != info.FullName)
                {
                    this.tvLeft.Nodes.Clear();
                    loadSuccess = false;
                    listTask = new List<Task>();
                    info = GetFolderInfo(txtFolderPath.Text);
                    new TaskFactory().StartNew(() => new TaskFactory().ContinueWhenAll(listTask.ToArray(), ts => { loadSuccess = true; }));
                }

                this.tvLeft.Nodes.AddRange(new TreeNode[] { SetTree(info) });
            }
        }

        private void btnSaveFolder_Click(object sender, EventArgs e)
        {
            var data = new sys_DirectoryInfo();
            if (info.FullName == txtFolderPath.Text || listTask.Count > 0)
            {
                if (loadSuccess == false)
                    Task.WaitAll(listTask.ToArray());
                data = info;
                loadSuccess = true;
            }
            else
            {
                loadSuccess = false;
                listTask = new List<Task>();
                data = GetFolderInfo(txtFolderPath.Text);
                Task.WaitAll(listTask.ToArray());
                data = info;
                loadSuccess = true;
            }
            BLLDirectoryInfo bll = new BLLDirectoryInfo();
            bll.SaveDirectory(data);
        }

        private void btnInitDirectoryInfo_Click(object sender, EventArgs e)
        {
            BLLDirectoryInfo bll = new BLLDirectoryInfo();
            bool bol = bll.InitTable();
            Common.Msg.Log.GetLog.Info(string.Format("初始化表{0}", bol ? "成功" : "失败"));
            MessageBox.Show(string.Format("初始化表{0}", bol ? "成功" : "失败"));
        }
    }
}
